package com.quan.upms.rpc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.quan.common.base.exception.BizException;
import com.quan.common.core.support.BaseService;
import com.quan.upms.rpc.api.UpmsMenuService;
import com.quan.upms.rpc.dao.mapper.UpmsMenuMapper;
import com.quan.upms.rpc.model.UpmsMenu;

@Service
public class UpmsMenuServiceImpl extends BaseService<UpmsMenu> implements UpmsMenuService {
	
	@Autowired
	private UpmsMenuMapper mapper ;
	
	@Override
	public int deleteById(Object id) throws BizException {
		return recursiveDelete(Integer.valueOf(id.toString()));
	}
	
	private int recursiveDelete(Integer id) {
		List<UpmsMenu> loadChildrenNode = this.selectChildren(id) ;
		if(null != loadChildrenNode) {
			for (UpmsMenu menu : loadChildrenNode) {
				recursiveDelete(menu.getId());
			}
		}
		return super.deleteById(id) ;
	}

	@Override
	public List<UpmsMenu> selectRoot() {
		return this.mapper.selectRoot();
	}

	@Override
	public List<UpmsMenu> selectChildren(Integer pid) {
		return this.mapper.selectChildren(pid);
	}

	@Override
	public List<UpmsMenu> tree(UpmsMenu entity) {
		List<UpmsMenu> list = new ArrayList<UpmsMenu>() ;
		
		List<UpmsMenu> selectRoot = this.selectRoot() ;
		for (UpmsMenu menu : selectRoot) {
			list.add(recursive(menu)) ;
		}
		return list;
	}
	
	private UpmsMenu recursive(UpmsMenu menu) {
		
		List<UpmsMenu> selectChildren = this.selectChildren(menu.getId()) ;
		if(null != selectChildren && !selectChildren.isEmpty()) {
			List<UpmsMenu> children = new ArrayList<UpmsMenu>() ;
			
			for (UpmsMenu childMenu : selectChildren) {
				children.add(recursive(childMenu)) ;
			}
			
			menu.setChildren(children);
		}
		return menu ;
	}

}
